package net.ufrog.common.utils;

import net.ufrog.common.Assert;
import net.ufrog.common.exception.ServiceException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 流工具类
 *
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-05-17
 * @since 0.1
 */
public class Streams {

    /** 构造函数 */
    private Streams() {}

    /**
     * 复制
     *
     * @param from 来源输入流
     * @param to 目标输出流
     */
    public static long copy(InputStream from, OutputStream to) {
        Assert.notNull(from);
        Assert.notNull(to);

        byte[] tmp = new byte[4096];
        long total = 0;
        while (true) {
            try {
                int len = from.read(tmp);
                if (len == -1) break;
                to.write(tmp, 0, len);
                total += len;
            } catch (IOException e) {
                throw new ServiceException(e.getMessage(), e);
            }
        }
        return total;
    }

    /**
     * 转化成字节数组
     *
     * @param in 输入流
     * @return 字节数组
     */
    public static byte[] toByteArray(InputStream in) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(Math.max(32, in.available()))) {
            copy(in, baos);
            return baos.toByteArray();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        }
    }
}
